package bing.lucene.helloworld;

import java.io.File;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.MultiFieldQueryParser;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;

/**
 * 参考案例：http://blog.csdn.net/liuyanlinglanq/article/details/42293243
 * 
 * @author trs
 *
 */
public class HelloWorld {

	//设置数据文件的路径
	File file=new File("C:\\Users\\trs\\git\\lucene-es-example\\data\\data.txt");
	//设置索引存放的路径
	File indexPath=new File("C:\\Users\\trs\\git\\lucene-es-example\\lucenceindex");
	
	//设置分词器为标准分词器
	Analyzer analyzer=new StandardAnalyzer();
	
	//创建索引，并存储到指定的路径下
	public void createIndex() throws Exception{
		Document doc=File2DocumentUtils.file2Document(file);
		
		//IndexWriterConfig(Version matchVersion, Analyzer analyzer) {
		IndexWriterConfig conf=new IndexWriterConfig(Version.LATEST, analyzer);
		IndexWriter indexWriter= new IndexWriter(new SimpleFSDirectory(indexPath),conf);
		
		indexWriter.addDocument(doc);
		
		indexWriter.close();
	}
	
	public void search(String queryWord) throws Exception{
		String[] fields= {"name","content"};
		
		QueryParser queryParse=new MultiFieldQueryParser(fields, analyzer);
		Query query=queryParse.parse(queryWord);
		
		IndexReader reader = DirectoryReader.open(FSDirectory.open(indexPath));
		IndexSearcher indexSearcher=new IndexSearcher(reader);
		
		Filter filter=null;
		//查询前100条记录
		TopDocs topDocs=indexSearcher.search(query, filter,100);
		
		System.out.println("共有["+topDocs.totalHits+"]条记录匹配");
		
		//将查询出的结果的scoreDocs遍历
		for(ScoreDoc scoreDoc:topDocs.scoreDocs) {
			int docSn=scoreDoc.doc;//文件的doc编号
			//根据编号，用indexSearcher查找到Document文件
			Document doc=indexSearcher.doc(docSn);
			//将document的内容打印出来。
			File2DocumentUtils.printDocumentInfo(doc);
		}
	}
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		HelloWorld hello=new HelloWorld();
		hello.createIndex();
		hello.search("room");
	}
	
	
	
	
	
	
	
	
	

}
